﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using HtmlAgilityPack;

namespace HTML
{
    public class HTMLDoc : IHTMLDoc, IEnumerable
    {
        public string _document { get; set; }
        public string rootUrl { get; set; }

        public IList<string> GetLinks()
        {
            var doc = new HtmlDocument();
            doc.Load(new StringReader(_document));
            var root = doc.DocumentNode;

            var tempUri = (new Uri(rootUrl)).AbsoluteUri;
            var anchorTags = new List<string>();
            var links = root.SelectNodes("//a");

            if (links != null)
            {
                foreach (HtmlNode link in links)
                {

                    string att = link.GetAttributeValue("href", "");
                    att = att.Replace(" ", "");

                    if (Uri.IsWellFormedUriString(att, UriKind.Absolute) && !att.Contains("javascript:") && !att.Contains("@") && !att.Contains("market://"))
                    {
                        anchorTags.Add(att);
                        //Console.WriteLine(att);
                    }

                    else if (!att.Contains("@") && !att.Contains("market://") && !att.Contains("javascript:"))
                    {
                        
                        int index = tempUri.Length - (tempUri.Length - tempUri.LastIndexOf("/")); //skal lige kigges på
                        string absoluteLink = tempUri.Substring(0, index + 1) + att;

                        Console.WriteLine(absoluteLink);
                        anchorTags.Add(absoluteLink);

                    }

                }
            }
            return anchorTags;
        }

        public IList<string> GetLinksRegEx()
        {
            List<String> links = new List<string>();

            MatchCollection mc = Regex.Matches(_document, @"href=\""(.*?)\""");
            //MatchCollection mc = Regex.Matches(_document, @"href=\""http:(.*?)\""|href=\""https:(.*?)\""");

            foreach (Match m in mc)
            {
                if (m != null)
                {
                    string tempStr = m.ToString();
                    tempStr = tempStr.Substring(6, tempStr.Length - 7);
                    links.Add(tempStr);
                }
            }

            return links;
        }

 
        public IEnumerator GetEnumerator()
        {
            throw new NotImplementedException();
        }
    }
}
